package com.lyc.service;

import com.lyc.dao.StockDao;
import com.lyc.entity.Stock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author ：Xiaochen
 * @date ：Created in 2022/12/8 22:35
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class StockService02 {
    @Autowired
    private StockDao stockDao;

    @Autowired
    private StringRedisTemplate redisTemplate;


    //减库存
    public String decrement(Integer productid) {
        ValueOperations<String, String> forValue = redisTemplate.opsForValue();
        //获取锁对象: 如果返回true表示获取锁成功,如果返回false 获取锁失败
        Boolean flag = forValue.setIfAbsent("product::" + productid, "aaa", 30, TimeUnit.SECONDS);
        if(flag) {
            try {
                //1. 查找指定商品的库存
                Stock stock = stockDao.selectById(productid);
                //2. 判断库存数是否大于0
                if (stock.getStock() > 0) {

                    //3.减库存
                    stock.setStock(stock.getStock() - 1);
                    stockDao.updateById(stock);
                    System.out.println("商品编号为:" + productid + "的商品库存剩余:" + stock.getStock() + "个");
                    return "商品编号为:" + productid + "的商品库存剩余:" + stock.getStock() + "个";
                } else {
                    System.out.println("商品编号为:" + productid + "的商品库存不足。");
                    return "商品编号为:" + productid + "的商品库存不足。";
                }
            }finally {
                //释放锁资源
                redisTemplate.delete("product::"+productid);
            }
        }else{
            //当前线程获取锁失败---->根据业务需求。
            System.out.println("服务器正忙,请稍后再试.....");
            return "服务器正忙,请稍后再试.....";
        }

    }
}